<!--
 * @Description：基础管理--后台角色管理--授权
 * @author： wlj
 * @date： 2025/05/28 16:28:08
!-->
<template>
  <el-dialog
    v-loading.fullscreen.lock="fullscreenLoading"
    title="授权页面"
    :visible.sync="dialogAuthorizedVisible"
    destroy-on-close
    lock-scroll
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    top="5vh"
    width="75%"
    class="auth-dialog"
    @close="handleSqDialogClose()"
  >
    <el-button type="default" class="can-btn" @click="CancelAuthuorize()">关 闭</el-button>
    <el-row :gutter="20">
      <el-col :span="8">
        <div class="auth-card">
          <div class="header">
            <div class="title">功能菜单</div>
            <el-button type="primary" @click="submitAuthuorize()">保 存</el-button>
          </div>
          <div style="margin-bottom: 10px;">注意：所有层级菜单需要手动勾选,一级菜单勾选才会显示菜单</div>
          <div class="ac-scoll">
            <el-form ref="formAuthorize" label-width="100px" @submit.native.prevent>
              <el-tree
                ref="sqMenuTree"
                :props="treeProps"
                :data="menu_tree_data"
                highlight-current
                accordion
                default-expand-all
                :expand-on-click-node="false"
                show-checkbox
                node-key="id"
                check-strictly
                :default-checked-keys="infoMenuUuids"
              />
            </el-form>
          </div>
        </div>
      </el-col>
      <el-col :span="16">
        <div class="auth-card">
          <div class="header">
            <div class="title">用户列表</div>
            <el-button type="primary" @click="handleConfirm()">保 存</el-button>
          </div>
          <el-form :inline="true" @submit.native.prevent>
            <el-form-item label="组织名称">
              <el-input v-model="listQuery.orgName" placeholder="请输入组织名称,回车搜索" style="width: 230px; text-align: right;" @keyup.enter.native="handleResetPage">
                <el-button slot="append" icon="el-icon-search" @click="handleResetPage" />
              </el-input>
            </el-form-item>
            <el-form-item label="姓名">
              <el-input v-model="listQuery.name" placeholder="请输入姓名,回车搜索" style="width: 230px; text-align: right;" @keyup.enter.native="handleResetPage">
                <el-button slot="append" icon="el-icon-search" @click="handleResetPage" />
              </el-input>
            </el-form-item>
          </el-form>
          <el-table
            ref="table"
            v-loading="listLoading"
            :data="userList"
            max-height="500px"
            border
            fit
            stripe
            @select="handleSelectionChange"
            @select-all="handleSelectionAll"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="组织名称" prop="orgName" show-overflow-tooltip />
            <el-table-column label="姓名" prop="name" />
            <el-table-column label="登录名称" prop="loginName" />
            <el-table-column label="性别" prop="gender">
              <template slot-scope="scope">
                {{ filterValue(global.userGenderList,scope.row.gender) }}
              </template>
            </el-table-column>
            <el-table-column label="账户过期时间" prop="userExpireTime" width="160">
              <template slot-scope="scope">
                {{ scope.row.userExpireTime || '永不过期' }}
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件 -->
          <div v-if="total > 0">
            <pagination
              :total="total"
              layout="total,sizes, prev, pager, next, jumper"
              :page-sizes="[5, 10, 20,30,50,80]"
              :page.sync="listQuery.page.pageIndex"
              :limit.sync="listQuery.page.pageSize"
              @pagination="search"
            />
          </div>
          <div v-if="userObjs.length > 0">
            <span>已勾选:</span>
            <div>
              <el-tag
                v-for="tag in userObjs"
                :key="tag.id"
                closable
                type="primary"
                effect="dark"
                style="margin-left: 10px;margin-top: 10px;"
                @close="handleCloseTag(tag)"
              >
                {{ tag.name }}
              </el-tag>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </el-dialog>

</template>
<script>
import { findPage } from '@/api/basic/sysUser'
import { moduleTree } from '@/api/basic/module'
import { getRoleModule, setRoleModule, getRoleUser, setRolesUser } from '@/api/basic/sysRole'
export default {
  name: 'RoleAssTable',
  props: {
    roleCode: { // 当前点击授权的角色code
      type: String,
      default: undefined
    },
    roleName: { // 当前点击授权的角色名称
      type: String,
      default: undefined
    },
    roleState: { // 当前点击授权的角色状态
      type: Number,
      default: undefined
    },
    platform: { // pc、admin
      type: String,
      default: undefined
    },
    userSelected: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      fullscreenLoading: false,
      menu_tree_data: [],
      // 查询已经拥有权限菜单的id
      infoMenuUuids: [],
      // 当前选中的所有权限菜单的id
      purviewUuids: [],
      // 选中的所有权限菜单的data
      purviewData: [],
      userList: [], // 用户列表
      userObjs: [],
      listLoading: false,
      listQuery: {
        orgName: '',
        name: '',
        status: 1,
        userExpireTimeValid: true,
        loginPlatform: 'ADMIN',
        page: {
          pageIndex: 1,
          pageSize: 10
        }
      },
      total: 0,
      dialogAuthorizedVisible: true,
      treeProps: {
        label: 'name'
        // disabled: (data, node) => {
        //   return this.roleCode === 'admin' && node.checked
        // }
      },
      dataCodeArr: []
    }
  },
  created() {
    this.handleAuthorize()
    this.getCheckUser()
  },
  methods: {
    // 授权菜单
    handleAuthorize() {
      // 查询角色的拥有的菜单权限
      getRoleModule({ roleCode: this.roleCode }).then(res => {
        res.data.forEach(item => {
          this.infoMenuUuids.push(item.code)
        })
        this.initMenuTree()
      }).catch(() => { })
    },
    // 获取菜单树数据
    initMenuTree() {
      moduleTree(this.platform).then(res => {
        this.menu_tree_data = res.data
      })
    },
    // 点击确认授权页面
    submitAuthuorize() {
      this.purviewData = this.$refs.sqMenuTree.getCheckedNodes()
      if (this.purviewData.length === 0) {
        this.$message({ message: '请选择需要授权的菜单！', type: 'warning' })
        return
      }
      this.$confirm('确定授权选定的菜单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.purviewUuids = []
        this.purviewData.forEach(row => {
          this.purviewUuids.push(row.code)
        })
        this.doPurview(this.purviewUuids)
      }).catch(() => {})
    },
    doPurview(purviewUuids) {
      this.fullscreenLoading = true
      setRoleModule({ menuCodes: purviewUuids, roleCode: this.roleCode }).then(res => {
        if (res.success) {
          this.$message({ message: '授权成功', type: 'success' })
          this.clearPurview()
        }
      }).catch(() => {
        this.fullscreenLoading = false
      })
    },
    // 清空权限的所有id数据
    clearPurview() {
      this.purviewUuids = []
      this.purviewData = []
      this.infoMenuUuids = []
      this.fullscreenLoading = false
    },
    // 关闭弹窗
    CancelAuthuorize(done) {
      this.$confirm('确认已保存后再关闭？')
        .then(_ => {
          this.clearPurview()
          this.userObjs = []
          this.listQuery.orgName = ''
          this.listQuery.name = ''
          this.$emit('cancel')
          done()
        }).catch(_ => {})
    },
    // 获取已选中的用户
    getCheckUser() {
      getRoleUser({ roleCode: this.roleCode }).then(res => {
        if (res.success) {
          this.userObjs = res.data.map(r => { return ({ name: r.name, loginName: r.loginName, id: r.userId }) })
          this.search()
        }
      })
    },
    // 保存--关联用户列表
    handleConfirm() {
      this.fullscreenLoading = true
      setRolesUser({
        rolePlatform: this.platform,
        roleName: this.roleName,
        roleCode: this.roleCode,
        userIds: this.userObjs.map(r => { return r.id }),
        status: this.roleState
      }).then(res => {
        if (res.success) {
          this.$message.success(this.userObjs.length > 0 ? '已成功关联用户' : '已取消该角色所有用户')
          this.fullscreenLoading = false
        }
      }).catch(() => {
        this.fullscreenLoading = false
      })
    },
    // 加载用户列表
    search() {
      this.listLoading = true
      findPage(this.listQuery).then(res => {
        if (res.data.rows) {
          this.userList = res.data.rows
        } else {
          this.userList = []
        }
        this.total = res.data.total
        if (this.userObjs.length > 0) {
          this.$nextTick(() => {
            this.userObjs.forEach(u => {
              this.userList.forEach(i => {
                if (u.id === i.id) {
                  this.$refs.table.toggleRowSelection(i, true)
                }
              })
            })
          })
        }
        this.listLoading = false
      }).catch(() => { this.listLoading = false })
    },
    // 多选的改变
    handleSelectionChange(selection, row) {
      // console.log('一个选的改变', selection, row)
      const ir = selection.findIndex(i => { return i.id === row.id })
      if (ir > -1) { // 选中
        const index = this.userObjs.findIndex(i => { return i.id === row.id })
        if (index <= -1) {
          this.userObjs.push(row)
        }
      } else { // 取消选中
        const index = this.userObjs.findIndex(i => { return i.id === row.id })
        if (index > -1) {
          this.userObjs.splice(index, 1)
        }
      }
    },
    // 全选的改变
    handleSelectionAll(selection) {
      // console.log('全选的改变', selection)
      if (selection.length === this.userList.length) { // 全选-选中
        this.userList.forEach(i => {
          if (this.userObjs.findIndex(u => { return u.id === i.id }) <= -1) {
            this.userObjs.push(i)
          }
        })
      } else { // 全部取消选中
        const newUserObjs = []
        this.userObjs.forEach(i => {
          if (this.userList.findIndex(u => { return u.id === i.id }) <= -1) {
            newUserObjs.push(i)
          }
        })
        this.userObjs = JSON.parse(JSON.stringify(newUserObjs))
      }
      console.log(this.userObjs)
    },
    // 关闭tag
    handleCloseTag(tag) {
      // console.log('关闭标签', tag)
      const index = this.userObjs.findIndex(i => { return i.id === tag.id })
      if (index > -1) {
        this.userObjs.splice(index, 1)
      }
      const index2 = this.userList.findIndex(i => { return i.id === tag.id })
      // console.log('列表的判断', index2)
      if (index2 > -1) {
        this.$nextTick(() => {
          this.$refs.table.toggleRowSelection(this.userList[index2], false)
        })
      }
    },
    // 切换搜索条件时，页码重置
    handleResetPage() {
      this.listQuery.page.pageIndex = 1
      this.search()
    }
  }
}
</script>
<style lang="scss" scoped>
.can-btn{
  position: absolute;
  top: 20px;
  right: 25px;
}
.auth-card{
  border: 1px solid #ccc;
  padding: 10px;
  min-height: 862px;
  .header{
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px  0;
    .title{
      font-size: 18px;
      font-weight: 600;
    }
  }
  .ac-scoll{
    max-height: 720px;
    overflow-y: auto;
  }
}
</style>
